package com.monika.main.system.util;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * @author:whh
 * @date: 2025-09-04 21:44
 * <p></p>
 */
public class FileUtil {



    public static final long DEFAULT_CHUNK = 1024 * 1024 * 100;//100MB  1024 * 1024 * 100

    private static long chunk = DEFAULT_CHUNK;

    /**
     * 对文件进行分块拆分以行分隔符为结尾
     * @param file
     * @return
     * @throws IOException
     */
    public static List<MappedByteBuffer> chunks(File file) throws IOException {

        try(RandomAccessFile r=new RandomAccessFile(file,"r");) {
            long length = r.length();
            List<MappedByteBuffer> chunks=new ArrayList<>((int) (length/chunk)+1);

            long start=0L;

            while (start<length){

                long pos=start+chunk;

                if(pos<length){
                    r.seek(pos);
                    do{
                        pos+=1;
                    }while (r.read()!='\n' && pos<length);
                }else {
                    pos=length;
                }
                MappedByteBuffer buffer = r.getChannel().map(FileChannel.MapMode.READ_ONLY, start, pos - start);
                buffer.order(ByteOrder.nativeOrder());
                chunks.add(buffer);
                start=pos;
            }

            return chunks;
        }catch (IOException e){
            throw e;
        }

    }
}
